<?php
/**
 * fenxiao.php
 *
 * Author: netman
 * DateTime:  2023/9/11 16:53
 */

class Service_Api_Fenxiao extends Contract_Api_Fenxiao
{
    use Trait_Api_Distributor;
    use Trait_Api_Image;

    /**
     * 获取预估利润
     * @param $typeid
     * @param $user_id
     * @param $product_id
     * @param $product_price
     * @return string
     * User: netman
     * Date: 2023/9/11 17:02
     */
    function get_estimate_profit($typeid, $user_id, $product_id, $product_price): string
    {
        $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid", '=', $user_id)->execute()->current();
        $commission_type = Model_Fenxiao_Config::get_val(
            'cfg_fenxiao_commission_type_'.$typeid,
            $fxgroupid['fxgroupid']
        );

        $maintable = DB::select('maintable')->from('model')->where('id', '=', $typeid)
            ->execute()
            ->get('maintable');
        $v['id'] = $product_id;
        list($profit,$suitid)=Model_Api_V2_Discount::get_profit_suitid($typeid,$v);
        $product['minprofit'] = $profit;
        $product['suitid'] = $suitid;

        //按订单金额百分比
        if ($commission_type == 1) {
            $commission_rate = Model_Fenxiao::get_commission_rate($typeid, $product_id, $fxgroupid['fxgroupid']);
            $v['commission'] = bcmul($commission_rate[0], '100');
            $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
            $v['commission'] .= '%';
            $v['profit'] = bcmul($product_price, $commission_rate[0]);
        } else {
            //按平台收入百分比
            if ($commission_type == 2) {
                $commission_rate = Model_Fenxiao::get_commission_rate_platform(
                    $typeid,
                    $product_id,
                    $fxgroupid['fxgroupid']
                );

                $v['commission'] = $commission_rate[0] * 100;
                $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                $v['commission'] .= '%';
                $temp_order = array(
                    'typeid' => $typeid,
                    'productautoid' => $product_id,
                    'suitid' => $product['suitid'],
                    'totalprice' => $product_price,
                    'channel_id' => 1,
                    'dingnum' => 1
                );
                $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                if($platform_price['settlement_type']==2){//销售价-获取销售最低价
                    $platform_price = $product_price;
                }else{//结算价模式-获取最低利润报价
                    $platform_price = $product['minprofit'];
                }

                $v['profit'] = $platform_price * $commission_rate[0];
            } else {
                //现金
                $commission_cash = Model_Fenxiao::get_commission_cash_line(
                    $typeid,
                    $product_id,
                    $fxgroupid['fxgroupid']
                );
                $v['commission'] = $commission_cash[0]['adult'];
                $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                $v['profit'] = $v['commission'];
            }
        }
        return $v['profit'];
    }

    /**
     * 分销商详情
     * @param $mid
     * @return mixed|void
     * User: netman
     * Date: 2023/9/21 9:41
     */
    function info($mid, $member)
    {
        $data = array();
        // 分销商信息
        $info = DB::select('isfrozen', 'fxcode', 'status')->from('fenxiao')->where('memberid', '=', $mid)
            ->execute()->current();
        if ( ! $info) {
            throw new Exception("您还不是分销商");
        }
        // 分销商状态
        if ($info['status'] != 1) {
            $data['fxstatus'] = $info['status'];
            return $data;
        }

        $data['isfrozen'] = $info['isfrozen'];
        $data['fxcode'] = $info['fxcode'];
        $data['fxstatus'] = $info['status'];
        // 会员信息
        $member_info = $member;
        $member_info['litpic'] = Model_Api_V2_Common::get_member_header_pic($member_info['litpic']);
        $data['member_info'] = array('litpic' => $member_info['litpic'], 'nickname' => $member_info['nickname']);

        // 可提现金额

        $data['tixian'] = number_format($member['money'] - $member['money_frozen'], 2, '.', '');

        // 我的分销商
        $data['fx_member_num'] = $this->get_member_num($mid);

        // 我的客户
        $data['member_num'] = $this->get_member_num($mid, 1);

        // 累计金额
        $total_profit = $this->get_total_profit($mid);
        //未完成结算金额
        $unfinish_profit = $this->get_total_unfinish_profit($mid);
        $total_profit += $unfinish_profit;
        $data['total_profit'] = Currency_Tool::price($total_profit);

        return $data;
    }

    /**
     * 是否是分销商
     * @param $params
     * @return false|mixed|null
     * User: netman
     * Date: 2023/9/21 10:52
     */
    function is_distributor($params)
    {
        $product_id = (int)$params['product_id'];
        $type_id = (int)$params['type_id'];
        $res = $this->check_member_distribution($params['mid']);
        $data = $res;
        //增加了一层产品是否分销的验证
        if ($product_id && $type_id) {
            $table = St_Functions::table_field($type_id);
            $fenxiao_status = DB::select('fenxiao_status')
                ->from($table[3])
                ->where('id', '=', $product_id)
                ->execute()
                ->get('fenxiao_status');
            $fenxiao_status = $fenxiao_status == 1 ? $res : array('isfenxiao'=>false);
            $data = $fenxiao_status;
        }
        return $data;
    }

    /**
     * 获取我的客户(非分销商)
     * @param $params
     * @return mixed|void
     * @throws Exception
     * User: netman
     * Date: 2023/9/21 11:29
     */
    function get_customer($params)
    {
        $info = $this->check_distribution($params['mid']);
        if ( ! $info) {
            throw new Exception('用户分销信息有误');
        }
        //条数
        $pagesize = (int)$params['pagesize'];
        //页码
        $page = (int)$params['page'];
        //关键词
        $keyword = $params['keyword'];
        $fxcode = $info['fxcode'];
        $params = array(
            'mid' => $params['mid'],
            'fxcode' => $fxcode,
            'page' => $page,
            'pagesize' => $pagesize,
            'keyword' => $keyword
        );
        $result = $this->get_submembers($params);
        return $result;
    }

    /**
     * 获取我发展的分销商
     * @param $params
     * @return mixed|void
     * User: netman
     * Date: 2023/9/21 11:33
     */
    function get_subfx($params)
    {
        $params = array(
            'mid' => $params['mid'],
            'group' => $params['group'],
            'page' => $params['page'],
            'pagesize' => $params['pagesize'],
            'keyword' => $params['keyword'] ?? ''
        );
        $result = $this->get_sub_distributor($params);
        return $result;
    }

    /**
     * 获得等级
     * @return int[]
     * User: netman
     * Date: 2023/9/21 11:32
     */
    function get_level(): array
    {
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $result = $level_num == 2 ? 2 : 3;
        return array('level_num' => $result);
    }

    /**
     * 成为分销商
     * @param $params
     * @return bool
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/21 14:07
     */
    function add_us($params)
    {
        $fxpcode = $params['fxpcode'];// 父级分销商
        $mid = $params['mid']; //当前会员
        $auto_verify = Model_Fenxiao_Config::get_val('cfg_fenxiao_autoverify', '');
        // 加入分销商
        $join_result = Model_Fenxiao::joinus($mid, $fxpcode);
        if ( ! $join_result) {
            throw new Exception('加入分销商失败');
        }
        // 分销商加入后续流程
        $fenxiao = ORM::factory('fenxiao')->where('memberid', '=', $mid)->find();

        if ($fenxiao->loaded()) {
            //分销商自动审核开关关闭  审核不通过
            if ($auto_verify == 0 && $fenxiao->status == 2) {
                $fenxiao->status = 0;
                $fenxiao->save();
            } elseif ($auto_verify == 1 && $fenxiao->status == 0)//分销商自动审核开关开启  等待审核
            {
                $fenxiao->status = 1;
                $fenxiao->verifytime = time();
                $fenxiao->fxrankid = Model_Fenxiao::get_rankid($mid);
                $fenxiao->save();
            } elseif ($auto_verify == 1 && $fenxiao->status == 2)//分销商自动审核开关开启  审核不通过
            {
                $fenxiao->status = 1;
                $fenxiao->verifytime = time();
                $fenxiao->fxrankid = Model_Fenxiao::get_rankid($mid);
                $fenxiao->save();
            }
        } else {
            throw new Exception("申请成为分销商失败");
        }
        return true;
    }

    /**
     * 获取产品列表
     * @param $params
     * @return mixed
     * User: netman
     * Date: 2023/9/21 16:33
     */
    function get_product($params)
    {
        $data = array(
            'mid' => $params['mid'],
            'keyword' => $params['keyword'] ?? '',
            'type_id' => $params['type_id'],
            'order_type' => $params['order_type'], //1综合排序2最热商品3价格由低到高4价格由高到低5最新商品
            'page' => Arr::get($params, 'page', 1),
            'pagesize' =>  Arr::get($params, 'pagesize', 10),
            'platform_no' =>  Arr::get($params, 'platform_no'),
        );
        return $this->get_products($data);
    }

    /**
     * 获取返佣订单
     * @param $params
     * @return array
     * User: netman
     * Date: 2023/9/21 16:41
     */
    function get_order($params)
    {
        $rank = (int)($params['rank'] ?? 0);
        $typeid = (int)($params['type_id'] ?? 0);
        $status = $params['status'] ?? 0;
        $mid = $params['mid'];
        $order = $params['order'] ?? 1;
        $keyword = $params['keyword'];
        $page = (int)($params['page'] ?? 1);
        $pagesize = (int)($params['pagesize'] ?? 10);
        $pagesize = $pagesize < 1 ? 10 : $pagesize;
        $offset = ($page - 1) * $pagesize;

        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $level_num = $level_num == 2 ? 2 : 3;
        $sub_mids = Model_Fenxiao::get_sub_mids($mid, $level_num);
        if ( ! empty($rank)) {
            // 自购订单
            if ($rank == '4') {
                $sub_mids = array($mid);
            } else {
                $sub_mids = Model_Fenxiao::get_sub_mids($mid, $rank, true);
            }
        } else {
            $sub_mids[] = $mid;
        }

        if ( ! empty($sub_mids) && ! empty($keyword)) {
            $keyword_submids = Model_Fenxiao::get_keyword_sub_mids($keyword);
            $keyword_w = ! empty($keyword_submids) ? " or mid in (".implode(',', $keyword_submids).")" : '';

            $sub_members = DB::query(
                Database::SELECT,
                "select mid from sline_member where mid in(".implode(
                    ',',
                    $sub_mids
                ).") and (mobile like '%{$keyword}%' or email like '%{$keyword}%' or nickname like '%{$keyword}%' {$keyword_w})"
            )->execute()->as_array();
            $sub_mids = array();
            foreach ($sub_members as $sub_member) {
                if ( ! empty($sub_member['mid'])) {
                    $sub_mids[] = $sub_member['mid'];
                }
            }
        }

        if (empty($sub_mids)) {
            return array('list' => array(), 'total' => 0);
        }
        $w = " where a.memberid in (".implode(',', $sub_mids).") ";
        if ( ! empty($typeid)) {
            $w .= " and a.typeid={$typeid} ";
        }

        if ( ! empty($status) || $status === 0 || $status === '0') {
            $w .= " and a.status='{$status}' ";
        }
        switch ($order) {
            case 2:
                $order_by = " order by ifnull(b.amount,0) desc,a.addtime desc ";
                break;
            case 3:
                $order_by = " order by ifnull(b.amount,0) asc,a.addtime desc ";
                break;
            default:
                $order_by = " order by a.addtime desc";
        }
        $sql = "select a.*,b.amount as fenxiao_amount,a.productname from sline_member_order a left join sline_fenxiao_record b on a.id=b.orderid and (b.memberid is null or b.memberid=".$mid.") {$w} {$order_by} limit {$offset},{$pagesize}";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        // 总条数
        $totalSql = "select count(*) as num from sline_member_order a left join sline_fenxiao_record b on a.id=b.orderid and (b.memberid is null or b.memberid=".$mid.") {$w}";
        $total = DB::query(Database::SELECT, $totalSql)->execute()->get('num');
        $result = array();
        foreach ($list as &$v) {
            $order = array();
            $model = ORM::factory('model', $v['typeid']);
            $table = $model->maintable;
            if ($table) {

                $info = ORM::factory($table, $v['productautoid'])->as_array();
                $out = $info;
                $order['litpic'] = $this->img_url($out['litpic']);

            }

            $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'], 0);
            $rank = Model_Fenxiao::get_rank($mid, $v['memberid']);
            $rank_index = $rank;
            $order['commission_type'] = $commission_type;
            $order_temp = Model_Member_Order::order_info($v['ordersn']);
            $commission_info = Model_Fenxiao::get_order_fenxiao_info($order_temp);

            if (empty($rank_index)) {
                $order['commission_amount'] = round($commission_info['commission'], 2);
            } else {
                $order['commission_amount'] = round($commission_info['commission'.$rank_index], 2);
            }

            $member_info = DB::select('mid','nickname')->from('member')->where('mid', '=', $v['memberid'])->execute()->current();
            $order['member'] = $member_info;
            $parent_fenxiao = Model_Fenxiao::get_ancestor_fenxiao($v['memberid'], 1);
            $order['parent_member'] = DB::select('mid','nickname')->from('member')->where('mid', '=', $parent_fenxiao['memberid'])->execute()->current();
            $order['addtime'] = date('Y-m-d H:i', $v['addtime']);
            $order['fenxiao_amount'] = empty($v['fenxiao_amount']) ? 0 : $v['fenxiao_amount'];
            $order['status_name'] = Model_Member_Order::get_status_name($v['status']);
            $order['ordersn'] = $v['ordersn'];
            $order['typeid'] = $v['typeid'];
            $order['totalprice'] = Model_Member_Order::order_total_price($v['id'], $v);
            $order['status'] = $v['status'];
            $order['productname'] = $v['productname'];
            $result[] = $order;
        }

        return array('list' => $result, 'total' => $total);
    }

    /**
     * 获取分销海报
     * @param $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/21 16:53
     */
    function get_distribution_poster($params)
    {
        // 检查是否开启图片分销
        $ways = Model_Fenxiao_Config::get_val('cfg_fenxiao_ways');
        $ways = explode(',', $ways);
        if ( ! in_array('pic', $ways)) {
            throw new Exception('不支持图片分销');
        }
        $id = (int)$params['product_id'];
        $typeid = (int)$params['type_id'];
        if ($typeid > 199) {
            $_t = 't';
        } else {
            $_t = 'typeid';
        }
        // 检查海报类型
        if ($id && $typeid) {
            // 高级海报
            $litpic = DB::select("litpic")->from("fenxiao_product")
                ->where("productid", "=", $id)
                ->and_where("typeid", "=", $typeid)
                ->execute()->get('litpic');

            $litpic = Model_Fenxiao::dowload_picture($litpic);
            // 分销基本参数
            $xurl = $params['url'];
            $comefrom = $params['comefrom'];//来源wechat微信小程序h5网页
            $mid = $params['mid'];
            $memberInfo = $params['member_info'];


            //获取头像
            $face_pic = ! empty($memberInfo['litpic']) ? $memberInfo['litpic'] : Common::member_nopic();
            $faceImg = Model_Fenxiao::dowload_picture($face_pic);
            $faceImg = $faceImg ? $faceImg : Common::member_nopic();
            // 获取产品分销二维码
            $codeRes = $this->get_product_code($xurl, $id, $mid, $comefrom, $_t);
            if ( ! $codeRes['status']) { // 获取失败
                throw new Exception($codeRes['msg']);
            }

            $codeImg = $codeRes['path'];
            // 检查背景图片是否存在
            if ( ! empty($litpic) && file_exists(BASEPATH.$litpic)) {
                // 高级海报
                $filename = md5($comefrom.$mid.$litpic.$id.$typeid).'.jpg';
                $path = "uploads/uniapp/distribution/product/{$comefrom}/".$filename;

                // 检查文件是否存在
                $savePath = BASEPATH.$path;
                $params = array(
                    'bg' => array(
                        'path' => BASEPATH.$litpic
                    ),
                    'codeImg' => array(
                        'path' => BASEPATH.$codeImg,
                    )
                );

                $username = $memberInfo['truename'] ? $memberInfo['truename'] : $memberInfo['nickname'];
                $params['username'] = array('text' => $username);
                //生成高级海报
                Model_Api_V2_Shareposter::best_poster($savePath, $params);
            } else {
                //产品基本信息
                $productinfo = St_Product::get_product_info($typeid, $id);
                $params = array();
                //获得模板类型
                $temple_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_pic_templet');
                if ($temple_type == 0)//标准海报
                {
                    $list = ORM::factory('fenxiao_config')->get_all();
                    $info = array();
                    foreach ($list as $v) {
                        $info[$v['varname']] = $v['value'];
                    }
                    $this->result['data'] = $info;
                    $pic_parts_arr = explode(',', $info['cfg_fenxiao_pic_parts']);
                    //logo
                    if (in_array('logo', $pic_parts_arr)) {
                        if($info['cfg_fenxiao_df_fx_shop_logo']){
                            $cfg_m_logo = Model_Fenxiao::dowload_picture($info['cfg_fenxiao_df_fx_shop_logo']);
                            $params['logo'] = array(
                                'path' => BASEPATH.$cfg_m_logo
                            );
                        }

                    }
                    //title
                    $params['title'] = array('text' => $productinfo['title']);
                    //sealPoint
                    if (in_array('sellpoint', $pic_parts_arr)) {
                        $params['sealPoint'] = array('text' => $productinfo['sellpoint']);
                    }
                    //useDate
                    if (in_array('date', $pic_parts_arr)) {
                        // 使用时间
                        $str = $this->get_product_price_date($id, $typeid);
                        $params['useDate'] = array('text' => $str);
                    }
                    //litpic
                    if (in_array('litpic', $pic_parts_arr)) {
                        $productinfo['litpic'] = Model_Fenxiao::dowload_picture($productinfo['litpic']);
                        $params['litpic'] = $productinfo['litpic'] ? array('path' => BASEPATH.$productinfo['litpic']) : '';
                    }
                    //piclist
                    if (in_array('piclist', $pic_parts_arr)) {
                        if ( ! empty($productinfo['piclist'])) {
                            $list = Product::pic_list($productinfo['piclist']);
                            $newarr = array();
                            foreach ($list as $key => $vel) {
                                $vel[0] = Model_Fenxiao::dowload_picture($vel[0]);
                                $picItem = BASEPATH.$vel[0];
                                if (isset($productinfo['litpic'])) { // 避免和封面重复
                                    if ($productinfo['litpic'] != $vel[0]) {
                                        array_push($newarr, $picItem);
                                    }
                                } else {
                                    array_push($newarr, $picItem);
                                }
                                // 只显示两张其余图片 避免过多导致生成过久及加载问题
                                if (count($newarr) > 1) {
                                    break;
                                }
                            }

                            $count = count($list);
                            $params['piclist'] = array(
                                'num' => $count,
                                'path' => $newarr
                            );
                        }
                    }
                    //tips
                    if (in_array('introduce', $pic_parts_arr)) {
                        $params['tips'] = array('text' => strip_tags($info['cfg_fenxiao_pic_introduce']));
                    }

                    //distribution
                    //没有分销商信息时依然显示二维码
                    $params['distribution'] = array(
                        'codeImg' => BASEPATH.$codeImg,
                        'username' => '',
                        'face' => '',
                        'account' => ''
                    );
                    if (in_array('fx', $pic_parts_arr)) {
                        //分销商数据
                        if ( ! empty($memberInfo['email'])) {
                            $accout = $memberInfo['email'];
                        }
                        if ( ! empty($memberInfo['mobile'])) {
                            $accout = $memberInfo['mobile'];
                        }
                        $username = $memberInfo['truename'] ? $memberInfo['truename'] : $memberInfo['nickname'];
                        $params['distribution'] = array(
                            'codeImg' => BASEPATH.$codeImg,
                            'username' => $username,
                            'face' => BASEPATH.$faceImg,
                            'account' => $accout
                        );
                    }
                    //price
                    $params['price'] = array('text' => (string)$productinfo['price']);

                    $filename = md5($comefrom.$mid.$litpic.$id.$typeid).'.jpg';
                    $path = "uploads/uniapp/distribution/product/{$comefrom}/".$filename;
                    $savePath = BASEPATH.$path;
                    Model_Api_V2_Shareposter::standard_mould1($savePath, $params);
//                    $this->send_datagrams($this->client_info['id'], Model_Api_V2_Shareposter::standard_mould1($savePath, $params), $this->client_info['secret_key']);
                } else {   //海报模板
                    $productinfo['litpic'] = Model_Fenxiao::dowload_picture($productinfo['litpic']);
                    $params['banner'] = array('path' => BASEPATH.$productinfo['litpic']);
                    $params['face'] = array('path' => BASEPATH.$faceImg);
                    $params['codeImg'] = array('path' => BASEPATH.$codeImg);
                    $params['price'] = array('text' => $productinfo['price']);
                    $params['title'] = array('text' => $productinfo['title']);
                    // 使用时间
                    $str = $this->get_product_price_date($id, $typeid);
                    $params['date'] = array('text' => $str);
                    $params['sealPoint'] = array('text' => $productinfo['sellpoint']);
                    // 用户信息
                    $username = $memberInfo['truename'] ? $memberInfo['truename'] : $memberInfo['nickname'];
                    $params['username'] = array('text' => $username);
                    if ( ! empty($memberInfo['email'])) {
                        $accout = $memberInfo['email'];
                    }
                    if ( ! empty($memberInfo['mobile'])) {
                        $accout = $memberInfo['mobile'];
                    }
                    $params['account'] = array('text' => $accout);
                    // 保存位置
                    $filename = md5($comefrom.$mid.$litpic.$id.$typeid).'.jpg';
                    $path = "uploads/uniapp/distribution/product/{$comefrom}/".$filename;
                    $savePath = BASEPATH.$path;
                    Model_Api_V2_Shareposter::standard_mould2($savePath, $params);
                }
            }
        }

        if ($path) {
            $resPath = Model_Api_V2_System::reorganized_resource_url($path);
            list($bgWidth, $bgHeight) = getimagesize($resPath); // 获取图片宽高
            $data = array(
                'path' => $resPath.'?time='.time(),
                'size' => array(
                    'w' => $bgWidth,
                    'h' => $bgHeight
                )
            );
            return $data;
        } else {
            throw new Exception('生成失败');
        }
    }

    /**
     * 订单查询条件
     * @param $params
     * @return mixed|void
     * User: netman
     * Date: 2023/9/21 16:55
     */
    function get_order_condition()
    {
        $model = $this->get_open_model();
        //全部订单条件
        $rank = array(
            array('id' => 0, 'name' => '全部订单'),
            array('id' => 1, 'name' => '我的一级分销订单'),
            array('id' => 2, 'name' => '我的二级分销订单'),
            array('id' => 3, 'name' => '我的三级分销订单'),
            array('id' => 4, 'name' => '自购佣金订单')
        );
        //订单状态
        $status = array(
            array('id' => '', 'name' => '所有订单'),
            array('id' => 0, 'name' => '待确认'),
            array('id' => 1, 'name' => '待付款'),
            array('id' => 2, 'name' => '待消费'),
            array('id' => 4, 'name' => '已退款'),
            array('id' => 5, 'name' => '已完成')
        );
        //排序
        $order = array(
            array('id' => '', 'name' => '综合排序'),
            array('id' => 1, 'name' => '下单时间倒序'),
            array('id' => 2, 'name' => '佣金由高到低'),
            array('id' => 3, 'name' => '佣金由低到高')
        );
        $tresult['model'] = $model;
        $tresult['rank'] = $rank;
        $tresult['status'] = $status;
        $tresult['order'] = $order;
        return $tresult;
    }

    function get_product_condition()
    {
        $model = $this->get_open_model();

        $sort = array_column($model, 'sort');
        array_multisort($sort, SORT_ASC, $model);

        $status = array(
            array('id' => 1, 'name' => '综合排序'),
            array('id' => 2, 'name' => '最热商品'),
//            array('id' => 3, 'name' => '收益由低到高'),
//            array('id' => 4, 'name' => '收益由高到低'),
            array('id' => 5, 'name' => '最新商品'),
        );
        $tresult['model'] = $model;
        $tresult['order'] = $status;
        return $tresult;
    }

    /**
     * 获取邀请海报
     * @param $params
     * @return array
     * @throws Exception
     * User: netman
     * Date: 2023/9/21 17:50
     */
    function get_invite_image($params)
    {
        $mid = $params['mid'];
        $comefrom = $params['comefrom'];
        $xurl = $params['url'];
        $filename = md5($comefrom.$mid).'.jpg';
        $path = "uploads/uniapp/distribution/{$comefrom}/".$filename;
        // 用户信息
        $member_info = $params['member_info'];
        $litpic = Model_Api_V2_Common::get_member_header_pic($member_info['litpic']);
        $litpic = Model_Fenxiao::dowload_picture($litpic);
        $litpic = $litpic ? $litpic : Common::member_nopic();
        // 检查文件是否存在
        $savePath = BASEPATH.$path;
        // 获取邀请二维码
        $codeRes = $this->get_invite_code($xurl, $comefrom, $mid);
        if ( ! $codeRes['status']) { // 获取失败
            throw new Exception($codeRes);
        }

        $codeImg = $codeRes['path'];
        $username = $member_info['nickname'] ? $member_info['nickname'] : $member_info['mobile'];
        $params = array(
            'face' => array(
                'path' => BASEPATH.$litpic
            ),
            'username' => array(
                'text' => $username ? $username.' 邀请您' : ' 邀请您'
            ),
            'codeImg' => array(
                'path' => BASEPATH.$codeImg,
            ),
            'inviteText' => array(
                'text' => $username.'邀请您，一起赚取海量佣金',
            ),
        );
        $result = Model_Api_V2_Shareposter::distribution_invite_poster($savePath, $params, $comefrom);
        if ($result['status'] == false) {
            throw new Exception($result['msg']);
        }
        $data = array(
            'path' => Model_Api_V2_System::reorganized_resource_url('/'.$path)
        );
        return $data;
    }

    /**
     * 获取分销商配置
     * @param $fields
     * @return array
     * User: netman
     * Date: 2023/9/22 9:50
     */
    function get_fenxiao_config($fields)
    {
        $data = array();
        if ($fields) {
            $filedArr = explode(',', $fields);
            foreach ($filedArr as $val) {
                $data[$val] = Model_Api_V2_Xcx::filter_content(Model_Fenxiao_Config::get_val($val));
            }
        }
        return $data;
    }


    /**
     * 获取链接
     * @param $params
     * @return mixed|void
     * User: netman
     * Date: 2023/9/22 10:03
     */
    function get_link($params)
    {
        $fenxiaoModel = DB::select()->from('fenxiao')->where('memberid', '=', $params['mid'])->execute()->current();
        $xurl = $params['url'];

        if(stripos($xurl,'&amp;fxpcode')){
            $index = stripos($xurl,'&amp;fxpcode');
            $xurl = substr($xurl,0,$index);
        }

        $product_id = $params['product_id'];
        $type_id = $params['type_id'];
        $product = St_Product::get_product_info($type_id, $product_id);
        $ways_arr = DB::select()->from('fenxiao_config')->where('varname', '=', 'cfg_fenxiao_ways')->execute()->current();
        $ways_arr = explode(',', $ways_arr['value']);
        if (!in_array('link', $ways_arr)) {
            return array('msg'=>'复制链接未打开');
        }
        $copylink_content = DB::select('value')->from('fenxiao_config')->where(
            'varname',
            '=',
            'cfg_weixin_copylink_content'
        )->execute()->get('value');
        $replacearr = array(
            'TITLE' => $product['title'],
            'LINK' => $xurl.'&fxpcode='.$fenxiaoModel['fxcode'],
            'PRICE' => $product['price'],
            'SELLPOINT' => $product['sellpoint']
        );
        foreach ($replacearr as $key => $val) {
            $copylink_content = str_replace('{#'.$key.'#}', $val, $copylink_content);
        }
        // 返回产品信息
        $info = array(
            'id' => $product['id'],
            'title' => $product['title'],
            'litpic' => $this->img_url($product['litpic']),
            'status' => $product['status']
        );
        $data = array(
            'contentstr' => $copylink_content,
            'productinfo' => $info,
            'share' => $replacearr
        );
        return $data;
    }

    function get_shop_code($params)
    {
        $mid = $params['mid'];
        $comefrom = $params['comefrom'];
        $xurl = $params['url'];

        $filename = md5($comefrom.$mid.$xurl).'.jpg';
        $path = "uploads/uniapp/distribution/shop/{$comefrom}/".$filename;

        // 用户信息
        $member_info = $params['member_info'];
        $litpic = Model_Api_V2_Common::get_member_header_pic($member_info['litpic']);
        $litpic = Model_Fenxiao::dowload_picture($litpic);
        $litpic = $litpic ? $litpic : Common::member_nopic();
        // 检查文件是否存在
        $savePath = BASEPATH.$path;
        // 获取邀请二维码
        $codeRes = $this->get_invite_code($xurl, $comefrom, $mid);
        if ( ! $codeRes['status']) { // 获取失败
            throw new Exception($codeRes['msg']);
        }

        $codeImg = $codeRes['path'];
        $mobile = $member_info['mobile'] ? substr_replace($member_info['mobile'], '****', 5, 4) : '';
        $amount = $mobile ? $mobile : $member_info['email'];
        $username = $member_info['nickname'] ? $member_info['nickname'] : $amount;
        $params = array(
            'face' => array(
                'path' => BASEPATH.$litpic
            ),
            'username' => array(
                'text' => $username
            ),
            'amount' => array( // 账号（手机号或邮箱）
                'text' => $member_info['nickname'] ? $amount : '' // 昵称存在时分享用户账号 不存在时用户名使用账号后 账号就不需要显示防止重复
            ),
            'codeImg' => array(
                'path' => BASEPATH.$codeImg,
            )
        );
        $result = Model_Api_V2_Shareposter::distribution_shop_poster($savePath, $params, $comefrom);
        if ($result['status'] == false) {
            throw new Exception($result['msg']);
        }
        return array('path' => St_Functions::get_main_host().'/'.$path);
    }


}